'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { updateRole } from '@/services/api';
import type { IDifference, IRole } from '@/interfaces';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateRoleInfo({
  source,
  translatedFields,
}: {
  source: IRole;
  translatedFields: PrefixedTTranslatedFields<'roleAdminPage'>;
}) {
  const [form, setForm] = useState<{
    name?: string;
    sort?: number;
    hide?: boolean;
  }>({
    name: source.name,
    sort: source.sort,
    hide: source.hide,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const { show } = useToast();
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateRoleMutation = useMutation(updateRole);

  useEffect(() => {
    const diffData = diff(
      {
        name: source.name,
        sort: source.sort,
        hide: source.hide,
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'sort') {
      setForm({ ...form, sort: parseInt(value) });
    } else if (name === 'hide') {
      setForm({ ...form, hide: value === 'true' });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();
      const data = getDiffData(differenceData);
      const id = source.id;
      await updateRoleMutation.mutateAsync({
        id,
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.update,
      });
    } catch (e) {
      updateRoleMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function checkForm() {
    const { name, hide } = form;

    if (!name) {
      throw translatedFields.tip.nameRequired;
    }

    if (!hide) {
      throw translatedFields.tip.hideRequired;
    }
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div>
          <label className="form-label">
            {translatedFields.properties.name}
          </label>
          <input
            type="text"
            className="form-control"
            name="name"
            value={form.name}
            onChange={onChangeForm}
            aria-describedby="name"
            placeholder={translatedFields.tip.namePlaceholder}
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.sort}
          </label>
          <input
            min={0}
            type="number"
            className="form-control"
            name="sort"
            value={form.sort}
            onChange={onChangeForm}
            aria-describedby="sort"
            placeholder={translatedFields.tip.sortPlaceholder}
          />
        </div>

        <div>
          <label className="form-label">
            {translatedFields.properties.hide}
          </label>
          <select
            name="hide"
            value={form.hide + ''}
            onChange={onChangeForm}
            className="form-select"
            aria-label="hide"
            placeholder={translatedFields.tip.hidePlaceholder}
          >
            <option value="false">false</option>
            <option value="true">true</option>
          </select>
        </div>

        <button
          type="submit"
          disabled={updateRoleMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateRoleMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
